package main

import (
	"reflect"
	"fmt"
)



func main()  {
	//test1()

	test2()
}

func test1()  {
	person := Person{"华华", "1996", 22, "北京"}
	map1 := StructToMap(person)
	fmt.Println(map1)
}

// 结构体  转 map
func StructToMap(bean interface{}) map[string]interface{} {
	rValue := reflect.ValueOf(bean)
	rType := reflect.TypeOf(bean)

	map1 := make(map[string]interface{})

	for i:=0; i< rValue.NumField(); i++ {
		vField := rValue.Field(i)
		tField := rType.Field(i)

		fmt.Println(vField, tField.Name)
		map1[tField.Name] = vField.Interface()
	}

	return map1

}

func test2()  {
	myMap := map[string]interface{}{"Name":"小二", "Age":12, "Sex":"男"}
	user := User{}
	MapToStruct(myMap, &user)

	fmt.Println(user)
}

func MapToStruct(myMap map[string]interface{}, bean interface{})  {

	rValue := reflect.ValueOf(bean)

	if rValue.Kind() != reflect.Ptr {
		fmt.Println("不是指针类型")
		return
	}

	elem := rValue.Elem()
	if !elem.CanSet() {
		fmt.Println("不能设置")
	}

	for key, value := range myMap {
		filed := elem.FieldByName(key)
		filed.Set(reflect.ValueOf(value))
	}

}







type Person struct {
	Name 		string
	Birthday 	string
	Age 		int
	Address 	string
}

type User struct {
	Name string
	Age int
	Sex string
}



